/*
 * @Author: fanjs
 * @Date: 2025-02-09 15:30:47
 * @Description: 公司简介
 */

import React, { useEffect, useState, useCallback } from 'react';

interface ImageProps {
  url: string;
}

const LazyImage: React.FC<ImageProps> = ({ url }) => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setIsVisible(true);
        observer.unobserve(entry.target);
      }
    });

    observer.observe(document.querySelector(`img[data-src="${url}"]`) as Element);

    return () => observer.disconnect();
  }, [url]);

  return (
    <img data-src={url} src={isVisible ? url : undefined} alt="" className="mt-2.5 block w-full h-auto" />
  );
};

const CompanyPage: React.FC = () => {
  const totalImages = 19;
  const initialLoadCount = 5;
  const [loadedImages, setLoadedImages] = useState<number>(initialLoadCount);

  /**
   * 加载更多图片
   * 每次加载3张,直到达到总数
   */
  const loadMoreImages = useCallback(() => {
    if (loadedImages < totalImages) {
      setLoadedImages(prevState =>
        Math.min(prevState + 3, totalImages));
    }
  }, [loadedImages, totalImages]);

  /**
   * 使用 IntersectionObserver 监听滚动到底部
   */
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          loadMoreImages();
        }
      },
      {
        root: null,
        rootMargin: '100px',
        threshold: 0.1,
      }
    );

    const sentinel = document.createElement('div');
    sentinel.style.height = '1px';
    document.querySelector('.company-container')?.appendChild(sentinel);
    observer.observe(sentinel);

    return () => {
      observer.disconnect();
      sentinel.remove();
    };
  }, [loadMoreImages]);

  return (
    <div className='p-2 h-screen overflow-y-auto company-container'>
      {Array.from({ length: loadedImages }).map((_, index) => (
        <LazyImage key={index} url={`/companyImgs/品味科技-公司简介_${(index + 1).toString().padStart(2, '0')}.png`} />
      ))}
    </div>
  );
};

export default CompanyPage;
